package com.Leetcode;

import java.util.LinkedList;
import java.util.Queue;

public class Index1765highestPeak {
	int[][] flag;
	public int[][] highestPeak(int[][] isWater) {
		int m = isWater.length,n = isWater[0].length;
		Queue<int[]> q = new LinkedList<>();
		flag = new int[m][n];
        for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if(isWater[i][j] == 1){
					q.offer(new int[] {i,j});
				    flag[i][j] = 1;
                    isWater[i][j] = 0;
                }
			}
		}
        while(!q.isEmpty()) {
        	int[] temp = q.poll();
        	int x = temp[0];
        	int y = temp[1];
        	if(isVisited(x+1, y)) { 
        		isWater[x+1][y] = isWater[x][y]+1;
        		q.offer(new int[] {x+1,y});
        		flag[x+1][y] = 1;
        	}
        	if(isVisited(x-1, y)) { 
        		isWater[x-1][y] = isWater[x][y]+1;
        		q.offer(new int[] {x-1,y});
        		flag[x-1][y] = 1;
        	}
        	if(isVisited(x, y+1)) { 
        		isWater[x][y+1] = isWater[x][y]+1;
        		q.offer(new int[] {x,y+1});
        		flag[x][y+1] = 1;
        	}
        	if(isVisited(x, y-1)) { 
        		isWater[x][y-1] = isWater[x][y]+1;
        		q.offer(new int[] {x,y-1});
        		flag[x][y-1] = 1;
        	}
        }
        return isWater;
    }
	
	public boolean isVisited(int i,int j) {
        if(i >= 0 && i < flag.length && j >= 0 && j < flag[0].length && flag[i][j] == 0)
            return true;
        else return false;
    }
}
